from php4dvd.model.user import User
#from php4dvd.model.film import Film
from php4dvd.pages.internal_page import InternalPage
from php4dvd.pages.add_film_page import AddFilmPage
from php4dvd.pages.IMDB_results_page import IMDBResultsPage
from php4dvd.pages.login_page import LoginPage
from php4dvd.pages.user_management_page import UserManagementPage
from php4dvd.pages.user_profile_page import UserProfilePage
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
#from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.expected_conditions import *
from selenium.webdriver.common.keys import Keys
import random
import time


class Application(object):
    def __init__(self, driver, base_url):
        driver.get(base_url)
        self.wait = WebDriverWait(driver, 30)
        self.login_page = LoginPage(driver, base_url)
        self.internal_page = InternalPage(driver, base_url)
        self.user_profile_page = UserProfilePage(driver, base_url)
        self.user_management_page = UserManagementPage(driver, base_url)
        self.add_film_page = AddFilmPage(driver, base_url)
        self.IMDB_results_page = IMDBResultsPage(driver, base_url)

    def logout(self):
        self.internal_page.logout_button.click()
        self.wait.until(alert_is_present()).accept()

    def ensure_logout(self):
        element = self.wait.until(presence_of_element_located(
            (By.CSS_SELECTOR, "nav, #loginform")))
        if element.tag_name == "nav":
            self.logout()

    def login(self, user):
        lp = self.login_page
        lp.is_this_page
        lp.username_field.send_keys(user.username)
        lp.password_field.send_keys(user.password)
        lp.submit_button.click()

    def ensure_login_as(self, user):
        element = self.wait.until(presence_of_element_located(
            (By.CSS_SELECTOR, "nav, #loginform")))
        if element.tag_name == "nav":
            # we are on internal page
            if self.is_logged_in_as(user):
                return
            else:
                self.logout()
        self.login(user)

    def is_logged_in(self):
        return self.internal_page.is_this_page

    def is_logged_in_as(self, user):
        return self.is_logged_in() \
            and self.get_logged_user().username == user.username

    def is_not_logged_in(self):
        return self.login_page.is_this_page

    def get_logged_user(self):
        self.internal_page.user_profile_link.click()
        upp = self.user_profile_page
        upp.is_this_page
        return User(
            username=upp.user_form.username_field.get_attribute("value"),
            email=upp.user_form.email_field.get_attribute("value"))

    def add_user(self, user):
        self.internal_page.user_management_link.click()
        ump = self.user_management_page
        ump.is_this_page
        ump.user_form.username_field.send_keys(user.username)
        ump.user_form.email_field.send_keys(user.email)
        ump.user_form.password_field.send_keys(user.password)
        ump.user_form.password1_field.send_keys(user.password)
        #ump.user_form.role_select.select_by_visible_text(user.role)
        ump.user_form.submit_button.click()

    def RandInt(self, maxval=10):
        return str(random.randint(1, maxval))

    def add_random_film(self, user):
        self.internal_page.home_link.click()
        self.internal_page.add_movie.click()
        add = self.add_film_page
        add.is_this_page
        add.IMDB_search_editbox.clear()
        add.IMDB_search_editbox.send_keys(self.RandInt(99))
        add.IMDB_submit_button.click()
        rez = self.IMDB_results_page
        temp = self.wait.until(lambda x: rez.is_this_page)
        rez.result_click(str(self.RandInt(20)), "2")
        temp = self.wait.until(lambda x: add.is_this_page)
        add.FillAllFieldsWith(
            "Added using Python2.7+Selenium2+PageObject model")
        add.film_form.save_button.click()
        if temp:
            print "Film [" + self.internal_page.film_name.encode(
                'cp866', errors='replace'
                ) + "] was added to your collection sucessfully"
        self.internal_page.home_link.click()

    def add_random_films(self, user, number=1):
        for i in range(number):
            self.add_random_film(user)
        print "[" + str(number) + "] films added sucessfully"

    def add_film(self, user, film):
        print "\n"+"Find & add: ",#
        print"Film: [" + film.film_name + "], year [" + str(
            film.film_year) + "], Use_IMDB = [" + str(film.use_imdb) + "]"
        self.internal_page.home_link.click()
        self.internal_page.add_movie.click()
        add = self.add_film_page
        add.is_this_page
        if film.use_imdb:
            add.IMDB_search_editbox.clear()
            add.IMDB_search_editbox.send_keys(
                "\"" + film.film_name + "\" " + str(film.film_year))
            add.IMDB_submit_button.click()
            rez = self.IMDB_results_page
            if rez.is_this_page:
                rez.result_click()
                temp = self.wait.until(lambda x: add.is_this_page)
                if temp:
                    add.film_form.save_button.click()
                    print "=>Film [" + self.internal_page.film_name.encode(
                        'cp866', errors='replace'
                        ) + "] was added to your collection sucessfully"
            else:
                print "=>No films found on IMDB with given parameters:"
                print "Film: [" + (film.film_name) + "], year [" + str(
                    film.film_year) + "]"
        else:
            add.film_form.name_editbox.clear
            add.film_form.name_editbox.send_keys(film.film_name)
            add.film_form.year_editbox.clear
            add.film_form.year_editbox.send_keys(film.film_year)
            add.film_form.save_button.click()
            time.sleep(1)
            if add.is_this_page:
                print "=>Total: " + str(
                    add.film_form.data_warnings_num()) + " warning(s)"
            else:
                print "=>Film [" + self.internal_page.film_name.encode(
                    'cp866', errors='replace'
                    ) + "] was added to your collection sucessfully"
        self.internal_page.home_link.click()

    def remove_films(self, user, film):
        print "\n" + "Search pattern= \"" + film.film_name \
            + "\"; Year less than [" + str(film.film_year) \
            + "]; IMDB Raiting less than [" + str(film.use_imdb) + "]"
        inp = self.internal_page
        inp.home_link.click()
        assert inp.is_this_page
        #jsn = inp.get_expando
        #hist = inp.run_js(self, jsn)
        inp.search_edit.clear()
        inp.search_edit.send_keys(film.film_name)
        time.sleep(1)
        inp.search_edit.send_keys(Keys.RETURN)
        print "inp.search_started = "+str(inp.search_started)
        try:
            inp.is_this_page
        except TimeoutException:
            print "###Search by text [" + (
                film.film_name) + "] returned TIMEOUT EXCEPTION"
        finally:
            print "###Search by text [" + film.film_name + "] returned [" \
                + str(len(inp.films_list)) + "] hits."
        getout = 1
        while len(inp.films_list) >= getout:
            if inp.delete_record(inp.films_list[getout - 1], film):
                getout = getout + 1
                print "=> Total films to keep =", str(getout - 1)
            inp.home_link.click()
            inp.is_this_page
